package demo3;

import java.util.Arrays;

// 泛型
public class MyStack<E> {
    public E[] elem;
    public int usedSize;

    public MyStack() {
        this.elem = (E[]) new Object[10];
    }

    /**
     * 入栈
     * @param val
     */
    public void push(E val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2*this.elem.length);
        }

        this.elem[this.usedSize++] = val;
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public E pop() {
        if (empty()) {
            throw new RuntimeException("栈为空");
        }

        E tmp = this.elem[this.usedSize-1];
        this.usedSize--;
        return tmp;
    }

    public boolean empty() {
        if (this.usedSize == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取栈顶元素不删除
     * @return
     */
    public E peek() {
        if (empty()) {
            throw new RuntimeException("栈为空");
        }

        return this.elem[this.usedSize-1];
    }

    public int getUsedSize() {
        return this.usedSize;
    }
}

